<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Pool\DataReader;
use ElfSundae\Laravel\Hashid\Facades\Hashid;
use Illuminate\Support\Facades\DB;
use App\Users\User;

class UpdateMiners extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'miners:update';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Update Miners and Users table when new active miners come in pool';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        //读取从矿池接口获取到的Json格式的矿工数据
        $dataReader = new DataReader();
        $minersData = $dataReader->getFastDataJson();
        //var_dump($minersData);
        $miners = $minersData['miners']??[];
        //var_dump($miners);

        //将矿工挖矿地址保存到$minersAddress数组中
        $minersAddress = [];
        foreach ($miners as $miner) {
            if ($miner['address'] == 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'){
                continue;
            }
            if (!in_array($miner['address'],$minersAddress) && $miner['status'] == 'active'){
                $minersAddress[] = $miner['address'];
            }
        }
        //查询users表中最大的id，此ID数据+1用来生成创建的新用户的Email地址
        $userMaxid = DB::table('users')
            ->selectraw('max(id) as maxid')
            ->first();
        $maxid = isset($userMaxid) ? $userMaxid->maxid : 0;
        //echo 'Max user id is : '.$maxid.'<br/>';

        foreach ($minersAddress as $address) {
            $existAddress = DB::table('miners')
                ->where('address',$address)
                ->first();
            //如果miners表中不存在当前挖矿地址记录，则首先在users表中为当前地址创建一个新用户，然后将当前矿工钱包地址添加到miners表中
            if (!isset($existAddress)){
                ++$maxid;
                $userEmail = hashid_encode($maxid).'@bmwpool.com';
                $newUser = new User([
                    'nick' => $address,
                    'email' => $userEmail,
                    'password' => bcrypt('123456'),
                ]);
                $newUser->administrator = 0;
                $newUser->active = true;
                $newUser->save();
                //在miners表中保存当前挖矿地址记录
                $newUser->miners()->create([
                    'address' => $address,
                    'note' => '用户：'.$userEmail.' 的挖矿地址'
                ]);

            }
        }
    }
}
